import { Component, PureComponent, createContext } from "react";

//1.
const UserContext = createContext({
  nickName: "默认",
  level: -1,
  region: 'China'
})

class Home extends PureComponent {
  render() {
    return <h2>{`用户名：${this.props.nickName} 等级：${this.props.level} 地区：${this.props.region}`}</h2>
  }
}

class About extends PureComponent {
  render() {
    return <h2>{`用户名：${this.props.nickName} 等级：${this.props.level} 地区：${this.props.region}`}</h2>
  }
}

class Detail extends PureComponent {
  render() {
    return (
      <ul>
        <li>{this.props.nickName}</li>
        <li>{this.props.level}</li>
        <li>{this.props.region}</li>
      </ul>
    )
  }
}

//3. 定义一个高阶组件
function WithUser(WrappedComponent) {
  return props => {
    return (
      <UserContext.Consumer>
        {
          user => {
            // console.log(user);
            //                        3.1 从user拿到数据对props进行增强
            return <WrappedComponent {...props} {...user} />
          } 
        }
      </UserContext.Consumer>
    )
  }
}

//4. 把组件传入 高阶组件
const UserHome = WithUser(Home)
const UserAbout = WithUser(About)
const UserDetail = WithUser(Detail)



class App extends Component {
  render() {
    return (
      <div>
        {/* 2. */}
        <UserContext.Provider value={{nickName: 'yzh', level: 999, region: '中国'}}>
          <UserHome />
          <UserAbout />
        </UserContext.Provider>

        <UserDetail />
      </div>
    )
  }
}

export default App